<?php
/**
 * @version 	$Id: fFolder.helper.php 74 2010-03-17 06:48:21Z mylifeisskidrow@gmail.com $
 * @author 		$Author: mylifeisskidrow@gmail.com $
 * @copyright 	Copyright (c) 2010 Luu Trong Hieu. All right reserved.
 * @license 	GNU/GPL see license.php
 */

defined('IN_FLYWHEEL') or die('Restricted Access');

/**
 * Folder Helper
 * 
 * @package 	system
 * @subpackage 	files_system
 *
 */
class fFolderHelper {
	/**
	 * Create
	 * 
	 * Tao folder, chmod
	 *
	 * @param string $path
	 * @param string $mode
	 */
	public static function create($path, $mode = '0777')
	{
		// Check if dir already exists		
		if (self::exists($path)) {
			return true;
		}
		$path = self::clean($path);
		static $nested = 0;
		
		//Kiểm tra thư mục cha.
		$parent = dirname($path);
		if(!self::exists($parent)) {
			$nested++;
			
			if (($nested > 20) || ($parent == $path)) {				
				$nested--;
				return false;
			}
			
			//create parent
			if (self::create($parent, $mode) !== true) {
				$nested--;
				return false;
			}
			$nested--;
		}
		
		@mkdir($path,$mode,true);
		return true;
	}
	
	/**
	 * Kiem tra xem co ton tai hay khong
	 *
	 * @param string $path
	 * @return boolean
	 */
	public static function exists($path)
	{
		return is_dir(self::clean($path));
	}
	
	/**
	 * Clean 
	 *  strip '/', '\' trong path
	 *
	 * @static
	 * @param	string	$path	Duong dan
	 * @param	string	$ds		Directory separator
	 * @return	string	The cleaned path
	 */
	public static function clean($path, $ds = _DS_)
	{
		$path = trim($path);

		if (empty($path)) {
			$path = ''; //wait for define
		} else {
			// Remove double slashes and backslahses and convert all slashes and backslashes to DS
			$path = preg_replace('#[/\\\\]+#', $ds, $path);
		}

		return $path;
	}
	
	/**
	 * Files
	 * lay danh sach file
	 *
	 * @param string $path duong dan
	 * @param string $filter filter mime type
	 * @param int $deep
	 * @param boolean $fullPath	 
	 * @return Array
	 */
	
	public static function files($path, $filter = '.', $deep = 1, $fullPath = false)
	{
		$arr = array();

		//Check path
		$path = self::clean($path);

		// Is the path a folder?
		if (!is_dir($path)) {
			return false;
		}

		// read the source directory
		$handle = opendir($path);
		while (($file = readdir($handle)) !== false)
		{
			if (($file != '.') && ($file != '..')) 
			{
				$dir = $path . DS . $file;				
				if (is_dir($dir))
				{
					$deep--;
					if ($deep !== 0) {
						$arr2 = self::files($dir, $filter, $deep, $fullPath);						
						$arr = array_merge($arr, $arr2);
					}
				} 
				else {
					if (strpos($file, $filter) !== false)
					{					
						if ($fullPath) {
							$arr[] = $path . DS . $file;
						} 
						else {
							$arr[] = $file;
						}
					}
				}
			}
		}
		closedir($handle);

		asort($arr);
		return $arr;
	}
}